<script setup>
import * as Cesium from 'cesium';
window.Cesium = Cesium;
import {onMounted} from "vue";

onMounted(() => {
  // const viewer = new Cesium.Viewer('cesiumContainer');
  var custom = new Cesium.ArcGisMapServerImageryProvider({
    url: "http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer"
  });
  var viewer = new Cesium.Viewer('cesiumContainer', {
    //不创建baseLayerPick小部件
    baseLayerPicker: false,
    //设置图像提供的程序
    imageryProvider: custom,
    //设置cesium世界地形
    terrainProvider: Cesium.createWorldTerrain({
      requestWaterMask: true,
      requestVertexNormals: true
    })
  });

  //广州
  // viewer.camera.setView({
  //   destination: Cesium.Cartesian3.fromDegrees(113.318977, 23.114155, 2000),
  //   //查看的方向和俯仰的视角
  //   orientation: {
  //     //方向
  //     heading: Cesium.Math.toRadians(90),
  //     //角度
  //     pitch: Cesium.Math.toRadians(0)
  //   }
  // });

  //纽约3d模型实例
  viewer.camera.setView({
    destination: new Cesium.Cartesian3(1332761, -4662399, 4137888),
    orientation: {
      heading: 0.60,
      pitch: -0.66
    }
  });

  //加载Cesium自带的3d模型
  var city = viewer.scene.primitives.add(new Cesium.Cesium3DTileset({
    url: Cesium.IonResource.fromAssetId(3839)
  }))

  //定义3d样式
  var heightStyle = new Cesium.Cesium3DTileStyle({
    color: {
      //条件判断,除了rgba也可以是rgb值
      conditions: [
        ['${height} >= 300','rgba(45,0,75,0.5)'],
        ['${height} >= 200','rgb(102,71,151)'],
        ['${height} >= 100','rgba(170,188,233,0.5)'],
        ['${height} >= 50','rgba(224,224,238,0.5)'],
        ['${height} >= 25','rgba(252,230,200,0.5)'],
        ['${height} >= 10','rgba(248,176,87,0.5)'],
        ['${height} >= 5','rgba(198,106,11,0.5)'],
        ['true','rgb(127,59,8)']
      ]
    }
  });

  city.style = heightStyle;

  //Geojson 文件加载
  var neighborHoodsPromise = Cesium.GeoJsonDataSource.load('src/assets/SampleData/sampleNeighborhoods.geojson');
  //加载进来后就是图形嘛，画好的区域
  var neihtborhoods;

  neighborHoodsPromise.then((dataSource) => {
    viewer.dataSources.add(dataSource);
    //把所有的实例放进来
    neihtborhoods = dataSource.entities;
    //这是一个数组
    var neihtborhoodsEntities = dataSource.entities.values;
    for (var i = 0; i < neihtborhoodsEntities.length; i++) {
      //拿到每一个基元
      var entity = neihtborhoodsEntities[i];
      //判断存不存在
      if (Cesium.defined(entity.polygon)) {
        //基元名称
        entity.name = entity.properties.neihtborhoods;
        // 设置多边形材质
        entity.polygon.material = Cesium.color.fromRandom({
          red: 0.1,
          maximumGreen: 0.9,
          maximumBlue: 0.9,
          alpha: 1
        });
        //进行着色操作
        entity.polygon.classificationType = Cesium.classificationType.TERRAIN;
        //将多边形的位置贴到最底下
        var polyPositions = entity.polygon.hierarchy.getValue(Cesium.JulianDate.now()).positions;
        //设置中心店
        var polyCenter = Cesium.BoundingSphere.fromPoints(polyPositions).center;
        //设置在地形的表面
        polyCenter = Cesium.Ellipsoid.WGS84.scaleToGeocentricSurface(polyCenter);
        //最终把基元的位置等于获取到的值
        entity.position = polyCenter;


        //生成标签
        entity.label = {
          text: entity.name,
          showBackground: true,
          scale: 0.6,
          horizontalOrigin:Cesium.horizontalOrigin.CENTER,
          verticalOrigin: Cesium.verticalOrigin.BOTTOM,
          //展示范围（条件）
          distanceDisplayCondition: new Cesium.distanceDisplayCondition(10, 8000),
          disableDepthTestDistance: 100
        };
      }
    }

  });


  //cesium 加载Kml
  var kmlOptions = {
    camera: viewer.scene.camera,
    canvas: viewer.scene.canvas,
    // 如果我们想将几何特征，（多边形，线串，和线性环）固定到地面上，则为true
    clampToGround: true
  }
  //kml 是谷歌公司创建的地标性文件
  //用于记录某一地点，或连续地点的时间，经度，纬度，海拔等地理信息数据，供GE 等有关软件使用

  var geocachePromise = Cesium.KmlDataSource.load("src/assets/SampleData/sampleGeocacheLocations.kml", kmlOptions);

  // 将geocache 广告牌实体添加到场景中并为其设置样式
  geocachePromise.then((dataSource) => {
    // 将新数据作为实体添加到查看器
    viewer.dataSources.add(dataSource);
    //获取实体数组
    var geocacheEntities = dataSource.entities.values;
    console.log(geocacheEntities, "数组");
    for (var i = 0; i < geocacheEntities.length; i++) {
      var entity = geocacheEntities[i];
      if (Cesium.defined(entity.billboard)) {
        //调整垂直原点， 使图钉于地形上
        entity.billboard.verticalOrigin = Cesium.VerticalOrigin.BOTTOM;
        entity.billboard.image = "src/assets/SampleData/yiyuan.png";
        //禁用标签以减少混乱
        entity.label = undefined;
        //添加距离显示条件
        entity.billboard.distanceDisplayCondition = new Cesium.DistanceDisplayCondition(10.0, 20000.0);
        //以度为单位计算纬度和经度
        var cartographicPosition = Cesium.Cartographic.fromCartesian(entity.position.getValue(Cesium.JulianDate.now()));
        var latitude = Cesium.Math.toDegrees(cartographicPosition.latitude);
        var longitude = Cesium.Math.toDegrees(cartographicPosition.longitude);
        //修改描述
        var description = '<table class="cesium-infoBox-defaultTable cesium-infoBox-defaultTable-lighter">' + '<tbody>' +
          '<tr><th>' + "Longitude" + '</th><td>' + longitude.toFixed(5) + '</td></tr>' +
          '<tr><th>' + "Longitude" + '</th><td>' + latitude.toFixed(5) + '</td></tr>' +
          '<tr><th>' + "实时人流" + '</th><td>' + Math.floor(Math.random() * 2000) + '</td></tr>' +
          '<tr><th>' + "安全等级" + '</th><td>' + Math.floor(Math.random() * 5) + '</td></tr>' +
          '</tbody></table>';
        entity.description = description;
      }

    }

  });


  //Cesium 从czml加载飞行路径
  var dronePromise = Cesium.CzmlDataSource.load("src/assets/SampleData/sampleFlight.czml");

  //无人机实体
  var drone;
  dronePromise.then((dataSource) => {
    viewer.dataSources.add(dataSource);
    drone = dataSource.entities.getById('Aircraft/Aircraft1');
    drone.model = {
      uri: "src/assets/SampleData/Models/CesiumDrone.gltf",
      minimumPixelSize: 128,
      maximumScale:1000,
      silhouetteColor: Cesium.Color.WHITE,
      silhouetteSize: 2
    };
    drone.orientation = new Cesium.VelocityOrientationProperty(drone.position);
    drone.viewFrom = new Cesium.Cartesian3(0, -30, 30);
    viewer.clock.shouldAnimate = true;
  });


});
</script>

<template>
  <div id="cesiumContainer"></div>
</template>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}
html,body,#cesiumContainer {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden;
}
</style>
